package com.oraycn.esbasic.loggers;

import android.telephony.mbms.FileInfo;
import android.util.Log;
import com.oraycn.esbasic.helpers.FileHelper;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileLogger implements ILogger {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String filePath="";
    private Boolean enabled = true;
    private long maxLength=Long.MAX_VALUE;//文件最大长度
    private FileWriter streamWriter;
    File file;
    private Object locker =new Object();
    public FileLogger(String filePath) {
        try {
            this.filePath = filePath;
            file = new File(this.filePath);//这是文件路径
            Boolean created = false;
            if (!file.exists())//如果不存在该目录
            {
                File path = new File(file.getParent());
                if( !path.exists()) {
                    path.mkdirs();
                }
                created = file.createNewFile();//这个方法是创建文件的方法
            }
            streamWriter=new FileWriter(this.file, !created);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void logWithTime(String msg) {
        this.write(dateFormat.format(new Date())+  " : "+msg  +"\n");
    }

    @Override
    public void logError(Exception ee) {
        this.logWithTime(Log.getStackTraceString(ee));
    }

    @Override
    public void setEnabled(Boolean _enabled) {
        this.enabled=_enabled;
    }

    @Override
    public Boolean getEnabled() {
        return this.enabled;
    }

    public void setMaxLength(long _maxLength)
    {
        if(_maxLength<=0)
        {
            throw new IllegalArgumentException("MaxLength must greater than 0.");
        }
        this.maxLength=_maxLength;
    }

    private void write(String msg)
    {
        if(!this.enabled)
        {
            return;
        }
        if(this.streamWriter==null){
            return;
        }
        synchronized(this.locker)
        {
            try {
                this.checkAndChangeNewFile();
                this.streamWriter.write(msg);//write()里可以写任意字符串
                this.streamWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void checkAndChangeNewFile()
    {
        try {
            if (this.file.length() >= this.maxLength)
            {
                this.streamWriter.close();
                this.streamWriter = null;
                String fileName = FileHelper.getFileName(this.filePath);
                String dir = FileHelper.getFileDirectory(this.filePath);
                int pos = fileName.lastIndexOf('.');
                String extendName = null;
                String pureName = fileName;
                if (pos >=0)
                {
                    extendName = fileName.substring(pos+1);
                    pureName = fileName.substring(0, pos);
                }
                String newPath = null;
                for(int i=1;i<1000;i++)
                {
                    String newName = pureName + "_" + String.valueOf(i);
                    if (extendName != null)
                    {
                        newName += "." + extendName;
                    }
                    newPath = dir + "/" + newName;
                    File f=new File(newPath);
                    if(f.exists())
                    {
                        if (f.length() < this.maxLength)
                        {
                            f.createNewFile();//这个方法是创建文件的方法
                            this.file=f;
                            break;
                        }
                    }else {
                        f.createNewFile();//这个方法是创建文件的方法
                        this.file=f;
                        break;
                    }
                }
                this.filePath=newPath;
                this.streamWriter = new FileWriter(this.file, true);// new StreamWriter(File.Open(newPath, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write, FileShare.Read));
            }
        }catch (Exception e)
        {

        }

    }

    private void close()
    {
        if(this.streamWriter!=null)
        {
            try {
                this.streamWriter.close();
                this.streamWriter=null;
            }catch (IOException e){

            }
        }
    }

    @Override
    protected void finalize() throws Throwable {
        this.close();
        super.finalize();
    }
}
